package com.ruoyi.project.service.impl;

import java.util.*;

import com.ruoyi.agent.domain.dto.AmagentTree;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.domain.vo.AmProjectQueryVo;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.AmProjectMapper;
import com.ruoyi.project.domain.AmProject;
import com.ruoyi.project.service.IAmProjectService;

import static javax.swing.UIManager.put;

/**
 * 项目管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-07-28
 */
@Service
public class AmProjectServiceImpl implements IAmProjectService 
{
    @Autowired
    private AmProjectMapper amProjectMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 查询项目管理
     * 
     * @param id 项目管理ID
     * @return 项目管理
     */
    @Override
    public AmProject selectAmProjectById(Long id)
    {
        return amProjectMapper.selectAmProjectById(id);
    }

    /**
     * 项目导入
     *
     * @param list
     * @param updateSupport
     */
    @Override
    public String importProject(List<AmProject> list, boolean updateSupport, LoginUser loginUser) {
        List<SysDictData> dicts = sysDictDataMapper.selectDictDataByType("am_peoject_delivery_standard");
        list.forEach(amProject -> {
            amProject.setCreateBy(loginUser.getUser().getUserId()+"");
            amProject.setIpdName(loginUser.getUser().getDeptId());
            amProject.setImage("");
            amProject.setDeliveryStandard(SysDictData.castValueByLabel(dicts,amProject.getDeliveryStandardValue()));
            amProjectMapper.insertAmProject(amProject);
        });
        return "插入成功";

    }


    /**
     * 查询项目管理列表
     * 
     * @param amProject 项目管理
     * @return 项目管理
     */
    @Override
    public List<AmProject> selectAmProjectList(AmProjectQueryVo amProject)
    {
            amProject.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        return amProjectMapper.selectAmProjectList(amProject);
    }

    /**
     * 新增项目管理
     * 
     * @param amProject 项目管理
     * @return 结果
     */
    @Override
    public int insertAmProject(AmProject amProject)
    {
        List<String> list = amProjectMapper.selectAllAmProjectList();
        if (list.contains(amProject.getProjectName())){
            throw new CustomException("该项目名已存在,不可重复添加");
        }
        amProject.setCreateTime(DateUtils.getNowDate());
        return amProjectMapper.insertAmProject(amProject);
    }

    /**
     * 修改项目管理
     * 
     * @param amProject 项目管理
     * @return 结果
     */
    @Override
    public int updateAmProject(AmProject amProject)
    {
        List<String> list = amProjectMapper.selectAllAmProjectList();
        if (list.contains(amProject.getProjectName())){
            throw new CustomException("该项目名已存在,不可重复添加");
        }
        return amProjectMapper.updateAmProject(amProject);
    }

    /**
     * 批量删除项目管理
     * 
     * @param ids 需要删除的项目管理ID
     * @return 结果
     */
    @Override
    public int deleteAmProjectByIds(Long[] ids)
    {

        /** 删除用户关联的项目*/
        amProjectMapper.deleteCollections(ids);
        return amProjectMapper.deleteAmProjectByIds(ids);
    }

    @Override
    public List<String> selectAllAmProjectList() {
        return amProjectMapper.selectAllAmProjectList();
    }

    /**
     * 删除项目管理信息
     * 
     * @param id 项目管理ID
     * @return 结果
     */
    @Override
    public int deleteAmProjectById(Long id)
    {
        return amProjectMapper.deleteAmProjectById(id);
    }


    /**
     * 项目列表
     */
    @Override
    public List<HashMap<String, Object>> list() {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        return amProjectMapper.list(deptId);
    }

    /**
     * 项目tree
     */
    @Override
    public List<HashMap<String,Object>> getProjectTree() {

        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        return Arrays.asList(new HashMap<String, Object>(16){
            {
                put("hasBindProject", toTree(amProjectMapper.selectHasBindProject( null,deptId )));
                put("hasNotBindProject",toTree(amProjectMapper.selectHasNotBindProject(deptId)));
            }
        });
    }

    /**
     * 项目tree
     */
    @Override
    public List<HashMap<String,Object>> getProjectTree(Long commissionId) {

        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        return  toTree(amProjectMapper.selectHasBindProject(commissionId,deptId));
    }

    /**
     * 项目楼宇tree
     */
    @Override
    public List<HashMap<String, Object>> getProjectBuildingTree() {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        List<Map<String, Object>> maps = amProjectMapper.selectAllProject(deptId);


        Set<Object> buildingIds = new HashSet<Object>();
        // 楼宇
        List<HashMap<String,Object>> buildings = new ArrayList<HashMap<String, Object>>();
        // 先找到楼宇
        for (Map<String,Object> building : maps ){
            if (buildingIds.add(building.get("buildingId"))){
                buildings.add(new HashMap<String, Object>(16){
                    {
                        put("id",building.get("buildingId"));
                        put("pid",building.get("projectId"));
                        put("label",building.get("buildingName"));
                    }
                });
            }

        }

        // 找到项目
        List<HashMap<String,Object>> projects = new ArrayList<HashMap<String, Object>>();
        Set<Object> projectSet = new HashSet<Object>();
        for (Map<String,Object> building : maps ){
            if (projectSet.add(building.get("projectId"))){
                HashMap<String, Object>  map= new HashMap<>(16);
                map.put("id",building.get("projectId"));
                map.put("label",building.get("projectName"));
                projects.add(map);
            }
        }

        //楼宇放进项目
        for(HashMap<String, Object> project :projects){
            List<HashMap<String,Object>> childrens = new ArrayList<HashMap<String, Object>>();
            for(HashMap<String,Object> building :buildings){
                if (null == building.get("pid") || null == project.get("id")){
                    continue;
                }
                if (building.get("pid").equals(project.get("id"))){
                    building.remove("pid");
                    childrens.add(building);
                }
            }
            project.put("children",childrens);
        }

        return projects;
    }

    private List<HashMap<String,Object>> toTree(List<HashMap<String,Object>> list) {
        Set<Object> buildingIds = new HashSet<Object>();

		/**
		 * 已选中数据
		 */
		List<Integer> checked = new ArrayList<Integer>();
		// 楼宇
		List<HashMap<String, Object>> buildings = new ArrayList<HashMap<String, Object>>();
        // 先找到楼宇
        for (Map<String, Object> building : list) {

        	if ("true".equals(building.get("checked"))){
        		checked.add((Integer) building.get("housingId"));
			}
            if (buildingIds.add(building.get("buildingId"))) {
                buildings.add(new HashMap<String, Object>(16) {
                    {
                        put("id", building.get("buildingId"));
                        put("pid", building.get("projectId"));
                        put("label", building.get("buildingName"));
                    }
                });
            }

        }
        // 把房号放进楼宇
        for (Map<String, Object> building : buildings) {
            if (null == building.get("id")){
                continue;
            }
            List<HashMap<String, Object>> housings = new ArrayList<HashMap<String, Object>>();
            for (Map<String, Object> housing : list) {
                if (building.get("id").equals(housing.get("buildingId"))) {
                    housings.add(new HashMap<String, Object>() {
                        {
                            put("id", housing.get("housingId"));
                            put("label", housing.get("roomNumber"));
                        }
                    });
                }
            }
            building.put("children", housings);
        }

        // 找到房源
        Set<Object> projectIds = new HashSet<Object>();
        List<HashMap<String, Object>> projects = new ArrayList<HashMap<String, Object>>();
        // 先找到楼宇
        for (Map<String, Object> building : list) {
            if (projectIds.add(building.get("projectId"))) {
                projects.add(new HashMap<String, Object>(16) {
                    {
                        put("id", building.get("projectId"));
                        put("label", building.get("projectName"));
                    }
                });
            }
        }

        //楼宇放进项目
        for (HashMap<String, Object> project : projects) {
            List<HashMap<String, Object>> childrens = new ArrayList<HashMap<String, Object>>();
            for (HashMap<String, Object> building : buildings) {
                if (null == project.get("id") || null == building.get("pid")){
                    continue;
                }
                if (project.get("id").equals(building.get("pid"))) {
                    building.remove("pid");
                    childrens.add(building);
                }
            }
            project.put("children", childrens);
        }
        return Arrays.asList(new HashMap<String, Object>(16) {
            {
                put("checked", checked);
                put("projectTree",projects);
            }
        });
    }



    private List<AmagentTree> buildTree(List<AmagentTree> list , Long parentId){
        List<AmagentTree> amagentTrees = new ArrayList<AmagentTree>();
        for (AmagentTree amagentTree : list) {

            Long id = amagentTree.getId();
            Long pid = amagentTree.getParentId();
            if (parentId.equals(pid)) {
                List<AmagentTree> menuLists = buildTree(list, id);

                amagentTree.setChildren(menuLists);
                amagentTrees.add(amagentTree);
            }
        }
        return amagentTrees;
    }
 }
